<template>
  <div class="dorm-admin-dashboard">
    <el-row :gutter="20">
      <!-- 饼图部分 -->
      <el-col :xs="24" :sm="24" :md="10" :lg="8" :xl="8">
        <el-card class="pie-card">
          <div slot="header">
            <span>归宿情况统计</span>
            <el-button 
              size="mini" 
              style="float: right; padding: 3px 0" 
              type="text"
              @click="refreshPieChart">
              刷新
            </el-button>
          </div>
          <dormitory-pie-chart ref="pieChart" />
        </el-card>
      </el-col>

      <!-- 表格部分 -->
      <el-col :xs="24" :sm="24" :md="14" :lg="16" :xl="16">
        <el-card class="table-card">
          <div slot="header">
            <span>异常归宿学生名单</span>
            <div style="float: right;">
              <el-select 
                v-model="filterType" 
                placeholder="筛选类型" 
                size="mini"
                style="width: 100px; margin-right: 10px;"
                @change="handleFilterChange">
                <el-option label="全部" value="all"></el-option>
                <el-option label="晚归" value="晚归"></el-option>
                <el-option label="不归" value="不归"></el-option>
              </el-select>
              <el-button 
                size="mini" 
                icon="el-icon-refresh" 
                @click="refreshTable">
              </el-button>
            </div>
          </div>
          <el-table
            :data="tableData"
            style="width: 100%"
            height="400"
            border
            stripe
            v-loading="tableLoading">
            <el-table-column
              prop="studentName"
              label="姓名"
              width="100">
            </el-table-column>
            <el-table-column
              prop="studentId"
              label="学号"
              width="120">
            </el-table-column>
            <el-table-column
              prop="className"
              label="班级"
              width="150">
            </el-table-column>
            <el-table-column
              prop="roomId"
              label="宿舍号"
              width="100">
            </el-table-column>
            <el-table-column
              prop="checkType"
              label="类型"
              width="100">
              <template slot-scope="scope">
                <el-tag 
                  :type="scope.row.checkType === '晚归' ? 'warning' : 'danger'"
                  size="small">
                  {{ scope.row.checkType }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="时间"
              width="180">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.checkDate, scope.row.checkTime) }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button 
                  size="mini" 
                  @click="handleContact(scope.row)">
                  联系
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import DormitoryPieChart from '@/components/DormStatsChart'
import { getAbnormalStudents } from '@/api/stuinfo/attendancerecord'

export default {
  name: 'DormAdminDashboard',
  components: {
    DormitoryPieChart
  },
  data() {
    return {
      // 表格相关数据
      tableData: [],
      tableLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      filterType: 'all',
      
      // 错误提示
      errorMessage: null
    }
  },
  created() {
    // 初始化数据
    this.fetchTableData()
  },
  methods: {
   // 获取表格数据
fetchTableData() {
  this.tableLoading = true;
  this.errorMessage = null;
  
  const params = {
    pageNum: this.currentPage,
    pageSize: this.pageSize,
    type: this.filterType === 'all' ? null : this.filterType
  };
  
  getAbnormalStudents(params)
    .then(response => {
      console.log('响应数据:', response); // 打印响应数据，用于调试
      // 直接使用转换后的标准结构
      this.tableData = response.list.map(item => ({
        recordId: item.recordId || null,
        studentId: item.studentId || '未知学号',
        studentName: item.studentName || '未知姓名',
        className: item.className || '未分配班级',
        roomId: item.roomId || '未分配宿舍',
        checkType: item.checkType || '未知类型',
        checkDate: item.checkDate || null,
        checkTime: item.checkTime || null
      }));
      
      this.total = response.total || 0;
      
      if (this.tableData.length === 0 && this.total > 0) {
        this.$message.warning('获取到的数据为空，可能存在分页参数问题');
      }
    })
    .catch(error => {
      console.error('获取异常学生列表失败:', error);
      this.errorMessage = error.message || '获取数据失败，请稍后重试';
      this.$message.error(this.errorMessage);
      this.tableData = [];
      this.total = 0;
    })
    .finally(() => {
      this.tableLoading = false;
    });
},
    
    // 刷新饼图
    refreshPieChart() {
      this.$refs.pieChart.fetchData()
    },
    
    // 刷新表格
    refreshTable() {
      this.currentPage = 1
      this.fetchTableData()
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchTableData()
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchTableData()
    },
    
    // 筛选类型变化
    handleFilterChange() {
      this.currentPage = 1
      this.fetchTableData()
    },
    
    // 格式化日期时间
    formatDateTime(date, time) {
      if (!date) return ''
      
      try {
        // 处理日期部分
        const dateObj = new Date(date)
        const dateStr = `${dateObj.getFullYear()}-${
          (dateObj.getMonth() + 1).toString().padStart(2, '0')}-${
          dateObj.getDate().toString().padStart(2, '0')}`
        
        // 处理时间部分
        if (!time) return dateStr + ' (未归)'
        
        // 处理Time对象
        if (time instanceof Date) {
          return dateStr + ' ' + time.toTimeString().substring(0, 8)
        }
        
        // 处理字符串格式时间
        if (typeof time === 'string') {
          return dateStr + ' ' + time.substring(0, 8)
        }
        
        return dateStr
      } catch (e) {
        console.error('日期格式化错误:', e)
        return '日期格式错误'
      }
    },
    
    // 联系学生
    handleContact(student) {
      this.$confirm(`确定要联系学生 ${student.studentName} (${student.studentId}) 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success(`已联系学生 ${student.studentName}`)
        // 这里可以添加实际的联系逻辑
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dorm-admin-dashboard {
  padding: 20px;
  
  .el-card {
    margin-bottom: 20px;
    
    ::v-deep .el-card__body {
      padding: 15px;
    }
  }
  
  .pie-card {
    height: 500px;
  }
  
  .table-card {
    height: 500px;
    
    .pagination-container {
      margin-top: 15px;
      text-align: right;
    }
  }
  
  @media (max-width: 992px) {
    .el-col {
      margin-bottom: 20px;
    }
    
    .pie-card,
    .table-card {
      height: auto;
    }
  }
}
</style>